#!/bin/bash

# 引入配置文件
source config.sh

# 日志文件路径
LOG_FILE="$LOG_DIR/deploy-laravel.log"

# 创建日志目录
mkdir -p $LOG_DIR
touch $LOG_FILE

# 日志记录函数
log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | sudo tee -a $LOG_FILE
}

# 错误处理函数
error_exit() {
    log "ERROR: $1"
    exit 1
}

# 1. 克隆或更新代码
log "Setting up project directory..."
if [ -d "$PROJECT_DIR" ]; then
    log "Updating existing repository..."
    cd $PROJECT_DIR
    git pull origin $GIT_BRANCH || error_exit "Failed to pull latest code."
else
    log "Cloning repository..."
    git clone -b $GIT_BRANCH $GIT_REPO $PROJECT_DIR || error_exit "Failed to clone repository."
    cd $PROJECT_DIR
fi

# 2. 安装 Composer 依赖
log "Installing Composer dependencies..."
composer install --no-dev --optimize-autoloader --no-interaction --prefer-dist || error_exit "Failed to install Composer dependencies."

# 设置目录权限
log "Setting directory permissions..."
sudo chown -R www-data:www-data $PROJECT_DIR/storage $PROJECT_DIR/bootstrap/cache
sudo chmod -R 775 $PROJECT_DIR/storage $PROJECT_DIR/bootstrap/cache

# 3. 设置 Laravel 环境变量
log "Configuring .env file..."
cp .env.example .env

# 使用正则表达式进行通用替换
sed -i "s/^DB_DATABASE=.*/DB_DATABASE=$DB_NAME/" .env
sed -i "s/^DB_USERNAME=.*/DB_USERNAME=$DB_USER/" .env
sed -i "s/^DB_PASSWORD=.*/DB_PASSWORD=$DB_PASS/" .env
sed -i "s/^CACHE_STORE=.*/CACHE_STORE=redis/" .env
sed -i "s/^SESSION_DRIVER=.*/SESSION_DRIVER=redis/" .env
sed -i "s/^QUEUE_CONNECTION=.*/QUEUE_CONNECTION=redis/" .env
sed -i "s/^REDIS_HOST=.*/REDIS_HOST=$REDIS_HOST/" .env
sed -i "s/^REDIS_PORT=.*/REDIS_PORT=$REDIS_PORT/" .env
sed -i "s/^REDIS_PASSWORD=.*/REDIS_PASSWORD=$REDIS_PASSWORD/" .env

# 添加配置验证
log "Verifying environment configuration..."
grep "^DB_DATABASE=$DB_NAME" .env || error_exit "Failed to set DB_DATABASE"
grep "^DB_USERNAME=$DB_USER" .env || error_exit "Failed to set DB_USERNAME"
grep "^DB_PASSWORD=$DB_PASS" .env || error_exit "Failed to set DB_PASSWORD"

# 4. 生成应用密钥
log "Generating application key..."
php artisan key:generate || error_exit "Failed to generate application key."

# 5. 配置 MySQL 数据库
log "Configuring MySQL database..."
mysql -u root -p$DB_ROOT_PASS -e "CREATE DATABASE IF NOT EXISTS $DB_NAME;"
mysql -u root -p$DB_ROOT_PASS -e "CREATE USER IF NOT EXISTS '$DB_USER'@'localhost' IDENTIFIED BY '$DB_PASS';"
mysql -u root -p$DB_ROOT_PASS -e "GRANT ALL PRIVILEGES ON $DB_NAME.* TO '$DB_USER'@'localhost'; FLUSH PRIVILEGES;"

# 6. 运行数据库迁移
log "Running database migrations..."
php artisan migrate --force || error_exit "Failed to run migrations."

# 7. 配置 Nginx
log "Configuring Nginx..."
NGINX_CONF="/etc/nginx/sites-available/$DOMAIN.conf"

# 清理旧配置
sudo rm -f $NGINX_CONF
sudo rm -f /etc/nginx/sites-enabled/$DOMAIN.conf

# 生成 Nginx 配置文件
cat <<EOL | sudo tee $NGINX_CONF > /dev/null
server {
    listen 80;
    server_name $DOMAIN;
    root $PROJECT_DIR/public;

    index index.php index.html index.htm;

    location / {
        try_files \$uri \$uri/ /index.php?\$query_string;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php$PHP_VERSION-fpm.sock;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;  # 分割请求的 URI
        fastcgi_param SCRIPT_FILENAME \$document_root\$fastcgi_script_name;
        fastcgi_param PATH_INFO \$fastcgi_path_info;  # 传递 PATH_INFO
        include fastcgi_params;
    }

    location ~ /\.ht {
        deny all;
    }

    error_log /var/log/nginx/${DOMAIN}_error.log;
    access_log /var/log/nginx/${DOMAIN}_access.log;
}
EOL


# 启用 Nginx 配置
sudo ln -s $NGINX_CONF /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx || error_exit "Failed to reload Nginx."

# 8. 配置 Supervisor 管理队列
log "Configuring Supervisor for Laravel Queue..."
WORKER_LOG_DIR="/var/log/laravel-worker"
mkdir -p $WORKER_LOG_DIR
chown -R www-data:www-data $WORKER_LOG_DIR

# 生成 Supervisor 配置文件
cat <<EOL | sudo tee $SUPERVISOR_CONF > /dev/null
[program:laravel-worker]
process_name=%(program_name)s_%(process_num)02d
command=php $PROJECT_DIR/artisan queue:work --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=8
redirect_stderr=true
stdout_logfile=$WORKER_LOG_DIR/worker.log
stopwaitsecs=3600
EOL


cat <<EOL | sudo tee $REVERB_SUPERVISOR_CONF > /dev/null
[program:laravel-reverb]
process_name=%(program_name)s_%(process_num)02d
command=php $PROJECT_DIR/artisan reverb:start
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=1
redirect_stderr=true
stdout_logfile=$WORKER_LOG_DIR/reverb.log
stopwaitsecs=3600
EOL

# 10. 配置 Horizon (可选)
if [ "$USE_HORIZON" = true ]; then
    log "Configuring Laravel Horizon..."
#    composer require laravel/horizon --quiet
#    php artisan horizon:install

    cat <<EOL | sudo tee $HORIZON_SUPERVISOR_CONF > /dev/null
[program:laravel-horizon]
process_name=%(program_name)s_%(process_num)02d
command=php $PROJECT_DIR/artisan horizon
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=www-data
numprocs=1
redirect_stderr=true
stdout_logfile=$WORKER_LOG_DIR/horizon.log
stopwaitsecs=3600
EOL
else
    log "Skipping Horizon installation"
fi

# 11. 配置 Pulse (可选)
if [ "$USE_PULSE" = true ]; then
    log "Configuring Laravel Pulse..."
#    composer require laravel/pulse --quiet
#    sed -i "s/'storage' => 'database'/'storage' => 'database'/" config/pulse.php
#    php artisan migrate --force
else
    log "Skipping Pulse installation"
fi

# 12. 启动 Supervisor
log "Starting Supervisor services..."
sudo supervisorctl reread
sudo supervisorctl update

# 启动基础服务
sudo supervisorctl start laravel-worker:*
sudo supervisorctl start laravel-reverb:*

# 按需启动可选服务
[ "$USE_HORIZON" = true ] && sudo supervisorctl start laravel-horizon:*


# 13. 配置定时任务
log "Configuring cron job..."
(crontab -l 2>/dev/null; echo "* * * * * php $PROJECT_DIR/artisan schedule:run >> /dev/null 2>&1") | crontab -

log "Laravel project deployment completed successfully!"